import React, { PureComponent } from 'react';
import { message, Spin } from 'antd';
import { DATA_ENTRY, AdvancedSearch, FirstHeaderC, PrimaryC, NoQueryC, exportPDF, NoDataC, NextedTableC } from '../../../comps';

import { connect, routerRedux } from 'dva';
import moment from 'moment';
import InvestmentRange from './investmentRange'; //可投范围
import NoInvestmentRange from './noInvestmentRange'; //不可投范围
import ConcentrationControl from './concentrationControl'; //投资集中度控制
import LiquidityControl from './liquidityControl'; //流动性控制
import Leverage from './leverage'; //杠杆率控制
import CombinedDurationControl from './combinedDurationControl'; //组合久期控制
import DeviationControl from './deviationControl'; //偏离度控制
import DetailList from './detailList'; //明细列表
import Introduction from './Introduction'; //头部
import styles from './style.less';
import uuid from 'es6-uuid';

@connect(({ cashManagementReportM, productAGroupM, loading, globalM }) => ({
  cashManagementReportM,
  productAGroupM,
  loading,
  globalM,
}))
export default class CashReport extends PureComponent {
  state = {
    tradingDate: '',
    portfolioCodeList: [],
    portfolioCodeListName: [],
    storeName: {},
    exportLoading: false,
    img: null,
    detailData: undefined, //报告详情数据
    noDataMsg: undefined, //无报告数据提示
    allDetialStatus: false, //最后的明细列表是否展开
    hasWaring: false, //是否有警告
  };
  componentDidMount() {
    const {
      globalM: {
        dataDictionary: { CASH_MANAGEMENT_REPORT_TYPE = [] },
      },
    } = this.props;
    this.props.dispatch({
      type: 'cashManagementReportM/save',
      payload: {
        securityBondTypeList: CASH_MANAGEMENT_REPORT_TYPE,
      },
    });
    if (this.props.portfolioCodeList && this.props.portfolioCodeList.length) this.queryReport(this.props);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.timeStamp != nextProps.timeStamp) {
      if (nextProps.portfolioCodeList && nextProps.portfolioCodeList.length) this.queryReport(nextProps);
    }
  }
  //查询报告数据
  queryReport = (props) => {
    this.props.dispatch({
      type: 'cashManagementReportM/queryReport',
      payload: {
        time: props.time,
        portfolioCodeList: props.portfolioCodeList,
        templateId: this.props.type == 2 ? 'money' : undefined, //试算需要这个传参
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            //有报告 则返回0
            if (res.data) {
              let object = res.data;
              for (const key in object) {
                if (Object.hasOwnProperty.call(object, key)) {
                  const item = object[key];
                  let obj = {}; //用于判断多少条严重警告 偏离度下面 每个子项 有一个或者多个3的 视作一条
                  item?.map((x, index) => {
                    if (key == 'allDetial') {
                      x.key = uuid(16);
                    }
                    if (x?.dataSource && x?.dataSource?.length) {
                      x.showDetail = false;
                      if (x.dataSource) {
                        x.dataSource.map((child) => (child.id = uuid(16)));
                        //偏离度控制 查找是否有严重警告
                        if (key == 'deviationControl') {
                          x.dataSource.map((child) => {
                            if (!child.PLDinfoId) child.PLDinfoId = '';
                            if (child.PLDinfoId.indexOf(3) > -1) {
                              obj[index] = 1;
                            }
                          });
                          this.setState({
                            hasWaring: Object.keys(obj).length, //是否有警告
                          });
                        }
                      }
                    }
                  });
                  object[key] = [...item];
                }
              }
              this.setState({
                detailData: object || {},
                noDataMsg: undefined,
                msgInfo: res.msg,
              });
            }
          } else if (res.code == 1) {
            //无报告 返回1
            this.setState({
              detailData: undefined,
              noDataMsg: res.msg,
              hasWaring: false,
            });
          } else {
            this.setState({
              detailData: undefined,
              noDataMsg: undefined,
              hasWaring: false,
            });
            message.error(res.msg || '查询报告失败!');
          }
        } else {
          this.setState({
            detailData: undefined,
            noDataMsg: undefined,
            hasWaring: false,
          });
          message.error('查询报告失败!');
        }
      },
    });
  };

  is360Chrome = () => {
    const uas = navigator.userAgent.split(' ');
    let result = false;
    // 排除ua自带标志的双核浏览器, 余下chrome, chromium及360浏览器
    if (uas[uas.length - 1].indexOf('Safari') == -1) {
      return result;
    }
    for (const key in navigator.plugins) {
      if (!Object.prototype.hasOwnProperty.call(navigator.plugins, key)) {
        continue;
      }
      // np-mswmp.dll文件在chromium及chrome未查询到
      if (navigator.plugins[key].filename === 'np-mswmp.dll') {
        return true;
      }
    }
    return result;
  };
  detectZoom = () => {
    var ratio = 0,
      screen = window.screen,
      ua = navigator.userAgent.toLowerCase();

    if (ua.indexOf('Mac OS X') || ua.indexOf('Mac')) {
      ratio = window.outerWidth / window.innerWidth;
    } else {
      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } else {
        if (~ua.indexOf('msie')) {
          if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
          }
        } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
          ratio = window.outerWidth / window.innerWidth;
        }
      }
    }
    if (ratio) {
      ratio = Math.round(ratio * 100);
    }
    return ratio;
  };

  onExportpdf = () => {
    //导出之前 页面的明细 全部展开
    let object = this.state.detailData;
    if (object) {
      for (const key in object) {
        if (Object.hasOwnProperty.call(object, key)) {
          const item = object[key] || [];
          item?.map((x) => {
            if (x?.dataSource && x?.dataSource?.length) {
              x.showDetail = true;
            }
          });
          object[key] = [...item];
        }
      }
      this.setState({
        detailData: { ...object },
        allDetialStatus: true,
      });
    }
    //检查页面是否有缩放
    if (this.is360Chrome()) {
      //360浏览器特殊处理
      if (!(Math.abs(this.detectZoom() - 100) < 5)) {
        // 去除loading状态
        this.props.onDownloading && this.props.onDownloading(false);
        this.setState({
          start: false,
        });
        message.warning('请将页面缩放比例设置为100%后再进行导出！');
        return;
      }
    } else if (this.detectZoom() !== 100) {
      // 去除loading状态
      this.props.onDownloading && this.props.onDownloading(false);
      this.setState({
        start: false,
      });
      message.warning('请将页面缩放比例设置为100%后再进行导出！');
      return;
    }

    this.setState({ exportLoading: true });
    const pdf = new exportPDF();
    pdf.savePDF('CashManagementReportId', 'xjgl-pdf', `现金管理理财新规报告-${moment().format('YYYY-MM-DD')}`, (tyep) => {
      this.setState({ exportLoading: false });
    });
  };
  //明细状态变更
  changeData = (data, type) => {
    let detailData = this.state.detailData;
    detailData[type] = [...data];
    this.setState({
      detailData: { ...detailData },
    });
  };
  //跳转至组合试算
  goToPath = () => {
    let obj = {
      time: this.props.time,
      portfolioCodeList: this.props.portfolioCodeList,
      prouctGroupId: this.props.prouctGroupId,
      portfolioCodeListName: this.props.portfolioCodeListName,
      portfolioKey: this.props.portfolioKey,
    };
    sessionStorage.setItem('reportInfo', JSON.stringify(obj));
    this.props.dispatch(routerRedux.push(`/portfolioBuild/portfolioTrial`));
  };

  render() {
    const { detailData, allDetialStatus } = this.state;
    const { portfolioCodeList, time } = this.props;
    let show = false;
    if (portfolioCodeList?.length > 0 && time) {
      show = true;
    }

    return (
      <div className='cashManagementReport' style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Spin spinning={this.props.loading.effects['cashManagementReportM/queryReport'] == true}>
          {this.props.type == 1 && (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <PrimaryC
                title='导出'
                disabled={!this.props.timeStamp || this.state.noDataMsg}
                loading={this.state.exportLoading}
                onClick={() => this.onExportpdf()}
                style={{ margin: '20px 15px 20px 0' }}
              ></PrimaryC>
              <PrimaryC title='报告试算' onClick={this.goToPath}></PrimaryC>
            </div>
          )}
          <div className={show && !this.state.noDataMsg ? styles.wrapperLine : ''}>
            {/* style={{ width: '100%', overflow: 'scroll', flex: '1' }} */}
            {/* 添加 className='exportpdfreport' 引用table.less 里的样式解决表头最后一列导出无背景色的问题（需添加一个空列） */}
            {show ? (
              this.state.noDataMsg ? (
                <div>
                  <NoDataC title={this.state.noDataMsg} />
                </div>
              ) : (
                <div id='CashManagementReportId' className='exportpdfreport' style={{ width: '1301px', margin: '0 auto', paddingBottom: ' 20px' }}>
                  {/* 标题 */}
                  <Introduction type={this.props.type} hasWaring={this.state.hasWaring} msgInfo={this.state.msgInfo} {...this.props}></Introduction>
                  {/* 可投范围 */}
                  <InvestmentRange data={detailData?.controllableRange} changeData={(e) => this.changeData(e, 'controllableRange')}></InvestmentRange>
                  {/* 不可投范围 */}
                  <NoInvestmentRange data={detailData?.uncontrollableRange} changeData={(e) => this.changeData(e, 'uncontrollableRange')}></NoInvestmentRange>
                  {/* 投资集中度控制 */}
                  <ConcentrationControl data={detailData?.concentrationControl} changeData={(e) => this.changeData(e, 'concentrationControl')}></ConcentrationControl>
                  {/* 流动性控制 */}
                  <LiquidityControl data={detailData?.fluidity} changeData={(e) => this.changeData(e, 'fluidity')}></LiquidityControl>
                  {/* 杠杆率控制 */}
                  <Leverage data={detailData?.leverageRatio} changeData={(e) => this.changeData(e, 'leverageRatio')}></Leverage>
                  {/* 组合久期控制 */}
                  <CombinedDurationControl data={detailData?.portfolioDay} changeData={(e) => this.changeData(e, 'portfolioDay')}></CombinedDurationControl>
                  {/*偏离度控制 */}
                  <DeviationControl
                    hasWaring={this.state.hasWaring}
                    data={detailData?.deviationControl}
                    changeData={(e) => this.changeData(e, 'deviationControl')}
                  ></DeviationControl>
                  {/* 明细列表 */}
                  <DetailList
                    time={this.props.time}
                    portfolioCodeList={this.props.portfolioCodeList}
                    data={detailData?.allDetial}
                    showDetail={allDetialStatus}
                    showBtn={this.props.type == 2 ? false : !this.state.exportLoading}
                    changeStatus={(e) => {
                      this.setState({ allDetialStatus: e });
                    }}
                  ></DetailList>
                </div>
              )
            ) : (
              <div style={{ marginTop: '20px' }}>
                <NoQueryC></NoQueryC>
              </div>
            )}
          </div>
        </Spin>
      </div>
    );
  }
}
